import axios from "axios";
import { Message } from "element-ui";
import { getToken } from "@/utils/auth";
import baseURL from './baseURL';

const service = axios.create({
  baseURL: baseURL.webUrl,
  withCredentials: true,
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    console.log('error:', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    let res = response.data
    let msgs = 'error'
    if (res.code !== 200) {
      switch (res.code) {
        case 401:
          msgs = res.msg ? res.msg : '认证失败'
          logout()
          break;
        case 500:
          msgs = res.msg ? res.msg : '服务器遇到错误，无法完成请求'
          break;
        case 503:
          msgs = res.msg ? res.msg : '服务器目前无法使用'
          break;
        default:
          Message({
            message: msgs ? msgs : 'error',
            type: 'error',
            duration: 5 * 1000
          })
      }
    }
    return response.data
  },
  error => {
    Message({
      message: "网络连接失败",
      type: "warning",
      duration: 3 * 1000
    });
    console.log('err:', error)
  }
)

export default service
